package cn.calm.xhtml.menu;

import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.expressions.IEvaluationContext;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;

import cn.calm.xhtml.handler.NamespaceHandler;
import cn.calm.xhtml.nature.XhtmlNature;

public class AddXhtmlNature extends AbstractHandler {
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IEvaluationContext context = (IEvaluationContext) event
				.getApplicationContext();
		List<?> selectedprojects = (List<?>) context.getDefaultVariable();
		for (Object obj : selectedprojects) {
			IProject project = null;
			if(obj instanceof IProject){
				project=(IProject) obj;
			}else if(obj instanceof IJavaProject){
				project=((IJavaProject) obj).getProject();
			}
			if(project==null){
				continue;
			}
			try {
				IProjectDescription description = project.getDescription();
				String[] natures = description.getNatureIds();
				String[] newnatures = new String[natures.length + 1];
				System.arraycopy(natures, 0, newnatures, 0, natures.length);
				newnatures[natures.length] = XhtmlNature.XHTML_NATURE_ID;
				description.setNatureIds(newnatures);
				project.setDescription(description, null);
				NamespaceHandler.parseProject(JavaCore.create(project));
			} catch (CoreException ex) {
				// Do nothing
			}
		}
		return true;
	}

}
